import {promiseRequest, getOpenId ,bezier,go} from "../../../utils/index";
import { imgBaseUrl } from "../../../utils/config";
const app = getApp();
 
Page({
	data: {
		//StatusBar: app.globalData.StatusBar,
		//CustomBar: app.globalData.CustomBar,
		//hidden: true,
		imgBaseUrl:imgBaseUrl,
		shopcarts:[],
		allMoney:0,
		allNum:0,
	},
	onLoad: function (option) {
		//缓存获取购物车数据
		this.getShoppingCart();
	},
	onShow(){
    //缓存获取购物车数据
		this.getShoppingCart();
	},
	/**
   *缓存中获取购物信息
   */
  getShoppingCart(){
    let shopcarts = wx.getStorageSync('shopcarts');
		shopcarts = shopcarts ? JSON.parse(shopcarts) : [];
		this.setData({
      shopcarts:shopcarts
		})
		//计算购物车商品总数和总金额
		this.caclShopCart(shopcarts)
	},
	/**
   * 计算购物车商品总数和总金额
   */
  caclShopCart(shopcarts){
		let allMoney = 0;
		let allNum = 0;
		for (var i = 0; i < shopcarts.length; i++) {
			let shopcart = shopcarts[i];
			allMoney+=shopcart.sellerPrice * shopcart.num;
			allNum+=shopcart.num;
		}
		this.setData({
			allMoney: allMoney,
			allNum:allNum
		})
	},
	handleAdd(e){
		let shopcarts = this.data.shopcarts;
    let item = e.currentTarget.dataset.item;
    let indx = e.currentTarget.dataset.index;
    item.num = item.num ==undefined?0:item.num;
    item.num = item.num + 1;
    let num = 'shopcarts['+indx+'].num';
    this.setData({
      [num]:item.num,
		})
		this.caclShopCart(shopcarts);
		wx.setStorageSync('shopcarts', JSON.stringify(shopcarts));
	},
	handleReduce(e){
    let shopcarts = this.data.shopcarts;
    let item = e.currentTarget.dataset.item;
    let indx = e.currentTarget.dataset.index;
		item.num = item.num ==undefined?0:item.num;
		let num = 'shopcarts['+indx+'].num';
    if(item.num==0){
      item.num = 0;
    }else{
      item.num = item.num-1;
		}
		if(item.num<=0){
			let index = shopcarts.findIndex(gd => gd.goodId === item.goodId);
			shopcarts.splice(index, 1);
		}
		console.log(shopcarts);
    this.setData({
			shopcarts:shopcarts
		})
		this.caclShopCart(shopcarts);
		wx.setStorageSync('shopcarts', JSON.stringify(shopcarts));
  },
	/**
	 * 跳转首页
	 */
	goIndex(){
		go(1,'/pages/tabar/index/index');
	}
});